package com.shandiangou.crm.controller;

import com.shandiangou.crm.model.vo.OrderVo;
import com.shandiangou.crm.service.CrmService;
import com.shandiangou.crm.service.OrderService;
import com.shandiangou.crm.util.ExcelUtil;
import com.shandiangou.crm.util.VoValidatorUtil;
import com.shandiangou.crm.web.HttpResult;
import com.shandiangou.member.domain.UserDO;
import com.shandiangou.member.service.UserService;
import com.shandiangou.member.session.SdgSessionUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by jacky on 16/1/20.
 * 交易业务的Controllerc层
 */

@Controller
@RequestMapping("/crm/order")
public class OrderController {

    private static final Logger logger = LoggerFactory.getLogger(OrderController.class);

    @Autowired
    private UserService userService;//用户中心服务

    @Autowired
    private OrderService orderService;//交易服务

    @Autowired
    private CrmService crmService;//crm服务

    @InitBinder
    public void initBinder(ServletRequestDataBinder dataBinder) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        df.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(df, false));
    }

    /**
     * 获取用户信息
     *
     * @return
     */
    private UserDO getUser() {
        if (SdgSessionUtil.getUserMobile() != null) {
            String mobile = SdgSessionUtil.getUserMobile().toString();
            return userService.getUserByMobile(mobile);
        } else {
            return null;
        }
    }

    /**
     * 导出订单EXCEL
     *
     * @param orderVo
     * @param response
     * @return
     */
    @RequestMapping(value = "/exportOrderList")
    @ResponseBody
    public HttpResult exportOrderList(@ModelAttribute OrderVo orderVo, HttpServletResponse response) {

        try {
            UserDO oUserDO = getUser();
            if (oUserDO != null) {
                String validateStr = VoValidatorUtil.validateVo(orderVo);
                List<Map> rights = crmService.listRightValue("exportOrderList", oUserDO.getMobile());//获得白名单数据
                if (rights == null || rights.isEmpty()) {
                    return HttpResult.Failure(-98, "权限不足！");
                } else {
                    if (validateStr != null) {
                        return HttpResult.Failure(-9, validateStr);
                    }
                    if (orderVo.getGmtCreateEnd().getTime() - orderVo.getGmtCreateStart().getTime() < 0) {
                        return HttpResult.Failure(-8, "结束时间不能早于开始时间!");
                    }
                    if (orderVo.getGmtCreateEnd().getTime() - orderVo.getGmtCreateStart().getTime() > 604800000) {
                        return HttpResult.Failure(-8, "时间跨度不能超过7天!");
                    }
                    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd");
                    String fileName = formatter.format(orderVo.getGmtCreateStart()) + "-" + formatter.format(orderVo.getGmtCreateEnd()) + "订单清单";

                    ByteArrayOutputStream os = new ByteArrayOutputStream();

                    String columnNames[]={"biz_order_id","订单类型","城市","店铺ID","店铺","地标ID","买家ID","买家号码","买家昵称","在线支付类型","买家付款成功时间","商品名称","订单状态","小二","主管","预订送达","订单生成时间","购买数量","订单在线支付状态","收货地址","支付类型","订单原价","实付金额","满减金额","优惠券金额","特价金额","闪电侠服务费","配送费","配送方"};//列名
                    ExcelUtil.createWorkBook(orderService.listOrderList(orderVo), fileName,columnNames,columnNames).write(os);

                    byte[] content = os.toByteArray();
                    InputStream is = new ByteArrayInputStream(content);
                    response.reset();
                    response.setContentType("application/vnd.ms-excel;charset=utf-8");
                    response.setHeader("Content-Disposition", "attachment;filename=" + new String((fileName + ".xlsx").getBytes(), "iso-8859-1"));
                    ServletOutputStream out = response.getOutputStream();
                    BufferedInputStream bis = null;
                    BufferedOutputStream bos = null;
                    try {
                        bis = new BufferedInputStream(is);
                        bos = new BufferedOutputStream(out);
                        byte[] buff = new byte[2048];
                        int bytesRead;
                        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
                            bos.write(buff, 0, bytesRead);
                        }
                    } catch (final IOException e) {
                        throw e;
                    } finally {
                        if (bis != null)
                            bis.close();
                        if (bos != null)
                            bos.close();
                    }
                    return null;
                }
            } else {
                return HttpResult.Failure(-98, "权限不足！");
            }
        } catch (Exception e) {
            logger.error("exportOrderList", e);
            return HttpResult.Failure(-99, "操作异常！");
        }
    }
}
